<template>
  <view class="sell-showcase">
    <wd-navbar
      :bordered="false"
      placeholder
      safeAreaInsetTop
      left-arrow
      custom-style="background-color:#92beab;"
      custom-class="color:#fff"
    >
      <template #title>
        <view class="custom-title-style">售卖橱窗</view>
      </template>
      <template #capsule>
        <wd-navbar-capsule @back="handleBack" @back-home="handleBackHome" />
      </template>
    </wd-navbar>
    <view class="search-input-box" @click="handleSearch">
      <uni-icons type="search" size="16" color="#999"></uni-icons>
      <input
        class="search-input"
        placeholder="搜索衣物"
        focus
        confirm-type="search"
      />
    </view>
    <!-- 筛选标签 92beab-->
    <view class="filter-bar-grid">
      <view
        class="filter-tag"
        v-for="(tag, index) in tags"
        :key="index"
        :class="{ active: activeTag === tag.value }"
        @click="selectTag(tag.value)"
      >
        {{ tag.label }}
      </view>
    </view>
    <!-- 商品为空提示 -->
    <scroll-view
      scroll-y="true"
      class="goods-all"
      refresher-enabled="true"
      :refresher-triggered="refresherTriggered"
      @refresherrefresh="onPullDownRefresh"
      @scrolltolower="onReachBottom"
    >
      <!-- 商品列表 -->
      <view class="goods-list">
        <navigator
          class="goods-card"
          v-for="(item, index) in filteredGoods"
          :key="item.id"
          :url="`/pages/goods/goods?id=${item.id}`"
        >
          <image
            :src="getFullImagePath(item.imageUrls[0])"
            mode="aspectFill"
            class="goods-image"
          />
          <view class="goods-info">
            <view class="goods-top">
              <text class="goods-name"
                >{{ item.name }} {{ item.description }}</text
              >
            </view>
            <view class="content-box">
              <text class="goods-price">¥{{ item.price }}</text>
            </view>
            <view class="goods-bottom">
              <view class="goods-img">
                <image
                  :src="getFullImagePath(item.userAvatar)"
                  mode="scaleToFill"
                  class="images"
                />
              </view>
              <view class="goods-footer">
                <text
                  class="goods-status"
                  :class="item.statusSale === '1' ? 'onsale' : 'offsale'"
                >
                  {{ item.statusSale === "1" ? "已挂售" : "未挂售" }}
                </text>
                <text class="goods-season">{{ item.season }}</text>
              </view>
            </view>
          </view>
        </navigator>
      </view>
      <!-- 加载更多状态 -->
      <view class="loading-more" v-if="isLoadingMore">
        <text>加载更多...</text>
      </view>
      <!-- 没有更多数据 -->
      <view class="no-more-data" v-if="!hasMore && !isLoadingMore">
        <text>没有更多的商品了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from "vue";
import { avatarUrlImg } from "@/api/config/http";
import { onLoad } from "@dcloudio/uni-app";
import { getCategoryAPI } from "@/api/clothes";
import { postSale } from "@/api/goods";
const hasMore = ref(true); // 是否还有更多数据
const isLoadingMore = ref(false); // 加载更多状态
const refresherTriggered = ref(false); // 下拉刷新状态
const current = ref(1);
const size = ref(10);
const goodsList = ref<any[]>([]);
const baseImageUrl = avatarUrlImg;
const params = reactive({
  pageNum: 1,
  pageSize: 10,
});
const tags = ref<{ label: string; value: string }[]>([]);
const activeTag = ref("all");
// 筛选逻辑
const selectTag = (tagValue: string) => {
  activeTag.value = tagValue;
  // 切换标签时刷新列表
  fetchOrderRecords(true);
};

const filteredGoods = computed(() => {
  if (activeTag.value === "all") return goodsList.value;
  return goodsList.value.filter((item) => item.category === activeTag.value);
});

// 获取完整图片路径
const getFullImagePath = (path: string) => {
  if (!path) return "";
  return path.startsWith("http") ? path : baseImageUrl + path;
};

const fetchOrderRecords = (isRefresh = false) => {
  if (isRefresh) {
    current.value = 1;
    hasMore.value = true;
  }
  if (!hasMore.value) return;
  isLoadingMore.value = true;
  setTimeout(async () => {
    const res = await postSale({
      pageNum: current.value,
      pageSize: params.pageSize,
      name: "",
    });
    const dataList = res.data.records;
    const newRecords = dataList.map((item) => ({
      ...item,
    }));
    if (isRefresh) {
      goodsList.value = newRecords;
    } else {
      goodsList.value.push(...newRecords);
    }
    hasMore.value = newRecords.length >= size.value;
    current.value++;
    isLoadingMore.value = false;
    refresherTriggered.value = false;
  }, 1000);
};
const onPullDownRefresh = () => {
  refresherTriggered.value = true;
  fetchOrderRecords(true);
  uni.showToast({
    title: "刷新成功",
    icon: "success",
    duration: 300,
  });
};

// 滚动到底部处理
const onReachBottom = () => {
  if (hasMore.value && !isLoadingMore.value) {
    fetchOrderRecords();
  }
};
const fetchTags = async () => {
  const res: any = await getCategoryAPI();
  const categoryData = res.data;
  // 先加“全部”
  const newTags = [{ label: "全部", value: "all" }];
  // 遍历后端返回的对象，组合成数组
  for (const key in categoryData) {
    newTags.push({ label: categoryData[key], value: key });
  }
  tags.value = newTags;
};
//跳转搜索
const handleSearch = () => {
  uni.navigateTo({
    url: "/pages/sellShowcase/search/searchSell",
  });
};
const handleBack = () => {
  uni.navigateBack({});
};
const handleBackHome = () => {
  uni.reLaunch({
    url: "/pages/index/index",
  });
};
// 页面加载
onLoad(() => {
  fetchTags();
  fetchOrderRecords();
});

// 跳转详情
</script>

<style lang="scss">
page {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

.sell-showcase {
  // background: #f5f5f5;
  min-height: 100vh;

  .goods-all {
    height: 100vh;

    .goods-list {
      display: flex;
      flex-wrap: wrap;
      gap: 20rpx;
      margin: 0 20rpx;

      .goods-card {
        width: 48%;
        background: #fff;
        border-radius: 10rpx;
        overflow: hidden;
        box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
        margin-bottom: 12rpx;

        .goods-image {
          width: 100%;
          height: 250rpx;
          object-fit: cover;
        }

        .goods-info {
          padding: 10rpx;

          .goods-top {
            display: flex;
            height: 80rpx;

            .goods-name {
              font-size: 28rpx;
              font-weight: bold;
              color: #333;
              display: block;
              margin-bottom: 4rpx;
            }
          }

          .content-box {
            .goods-price {
              font-size: 28rpx;
              color: #ff4d4f;
              margin-bottom: 6rpx;
            }
          }

          .goods-bottom {
            display: flex;
            height: 100rpx;

            .goods-img {
              flex: 1;
              display: flex;
              align-items: center;

              .images {
                width: 80rpx;
                border-radius: 50%;
                height: 80rpx;
              }
            }

            .goods-footer {
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              align-items: center;

              .goods-status {
                font-size: 24rpx;
                padding: 2rpx 6rpx;
                border-radius: 4rpx;

                &.onsale {
                  color: #52c41a;
                  border: 1rpx solid #52c41a;
                }

                &.offsale {
                  color: #999;
                  border: 1rpx solid #ccc;
                }
              }

              .goods-season {
                font-size: 22rpx;
                color: #666;
              }
            }
          }
        }
      }
    }
  }
}

.filter-bar-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx; // 标签间距
  margin: 10rpx 20rpx;
  margin-bottom: 16rpx;

  .filter-tag {
    flex: 1 0 20%; // 每个标签占一行的 30%，三列布局
    text-align: center;
    padding: 12rpx 0;
    border-radius: 10rpx;
    background: #eee;
    font-size: 26rpx;
    color: #333;

    &.active {
      background: #92beab;
      color: #fff;
      font-weight: bold;
    }
  }
}

.loading-more {
  text-align: center;
  padding: 30rpx 0;
  font-size: 28rpx;
  color: #999;
}

.no-more-data {
  text-align: center;
  padding: 30rpx 0;
  font-size: 28rpx;
  color: #ccc;
}

.search-input-box {
  margin: 10rpx 50rpx;
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 20rpx;
  padding: 10rpx 20rpx;

  .search-input {
    flex: 1;
    margin: 0 16rpx;
    font-size: 28rpx;
    background: transparent;
    border: none;
    outline: none;
  }
}
</style>
